package cn.iocoder.yudao.module.scrm.service.receivable;

import cn.iocoder.yudao.module.scrm.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.scrm.dal.mysql.order.OrderMapper;
import cn.iocoder.yudao.module.scrm.enums.common.CrmBizTypeEnum;
import cn.iocoder.yudao.module.scrm.util.CheckNoGeneratorUtil;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.scrm.controller.admin.receivable.vo.*;
import cn.iocoder.yudao.module.scrm.dal.dataobject.receivable.ReceivableDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.scrm.dal.mysql.receivable.ReceivableMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.scrm.enums.ErrorCodeConstants.*;

/**
 * 回款 Service 实现类
 *
 * @author admin
 */
@Service
@Validated
public class ReceivableServiceImpl implements ReceivableService {

    @Resource
    private ReceivableMapper receivableMapper;

    @Resource
    private CheckNoGeneratorUtil checkNoGeneratorUtil;

    @Resource
    private OrderMapper orderMapper;

    @Override
    public Long createReceivable(ReceivableSaveReqVO createReqVO) {
        // 插入
        ReceivableDO receivable = BeanUtils.toBean(createReqVO, ReceivableDO.class);
        //设置回款编号
        //receivable.setNo(checkNoGeneratorUtil.generateUniqueCheckNo(CrmBizTypeEnum.CRM_RECEIVABLE.getType()));
        OrderDO orderDO = orderMapper.selectById(createReqVO.getOrderId());
        receivable.setNo(orderDO.getSystemNumber());
        receivable.setOwnerUserId(orderDO.getOwnerUserId());

        receivableMapper.insert(receivable);
        // 返回
        return receivable.getId();
    }

    @Override
    public void updateReceivable(ReceivableSaveReqVO updateReqVO) {
        // 校验存在
        validateReceivableExists(updateReqVO.getId());
        // 更新
        ReceivableDO updateObj = BeanUtils.toBean(updateReqVO, ReceivableDO.class);
        receivableMapper.updateById(updateObj);
    }

    @Override
    public void deleteReceivable(Long id) {
        // 校验存在
        validateReceivableExists(id);
        // 删除
        receivableMapper.deleteById(id);
    }

    private void validateReceivableExists(Long id) {
        if (receivableMapper.selectById(id) == null) {
            throw exception(RECEIVABLE_NOT_EXISTS);
        }
    }

    @Override
    public ReceivableDO getReceivable(Long id) {
        return receivableMapper.selectById(id);
    }

    @Override
    public PageResult<ReceivableDO> getReceivablePage(ReceivablePageReqVO pageReqVO) {
        return receivableMapper.selectPage(pageReqVO);
    }

}